using System;

namespace Shraga.Client
{
	/// <summary>
	/// Summary description for RegistryHandler.
	/// </summary>
	public class RegistryHandler
	{
		public RegistryHandler()
		{
		}

		public bool PlaceInRegistry(string name, int subvalue, string registryPath)
		{
			bool ret = true;
			try
			{
				Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(registryPath);
				int mask = 255;
				int sub = 0;
				//byte[] bytearr;
				byte[] bytearr = new byte[5];

				if (subvalue < 0)
				{
					bytearr[4] = 1;
					subvalue = -subvalue;
				}
				else
				{
					bytearr[4] = 0;
				}

				int i = 0;
				while (subvalue > 0)
				{
					sub = subvalue & mask;
					subvalue = subvalue >> 8;
					bytearr[i++] = Convert.ToByte(sub);
				}
				//key.SetValue(name, Convert.ToByte(subvalue));
				key.SetValue(name, bytearr);
			}
			catch
			{
				ret = false;
			}
			return ret;
		}

		public decimal ReadFromRegistry(string registryPath, string name)
		{
			decimal ret = -1;
			int subvalue = 0;
			int sub = 0;
			byte[] bytearr;
			int i = 0;
			try
			{
				Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(registryPath);
				//System.IO.MemoryStream ms = new System.IO.MemoryStream(4);
				bytearr = (byte[]) key.GetValue(name);

				for(i = bytearr.Length - 2; i >= 0; i--)
				{
					subvalue = subvalue << 8;
					sub = Convert.ToInt32(bytearr[i]);
					subvalue += sub;
				}

				if (Convert.ToInt16(bytearr[bytearr.Length - 1]) == 1)
				{
					subvalue = -subvalue;
				}

				ret = Convert.ToDecimal(subvalue);
			}
			catch
			{
				ret = -1;
			}
			return ret;
		}
	}
}